#!/bin/bash
# -*- encoding: utf8 -*-
#add by zhangdi at 2017-04-14 09:58:51

from config.database import mysqlconfig as database
import MySQLdb

class MyDB:
    def __init__(self,DbType):
        self.dbConf = {}
        for x in database[DbType]:
            if x not in self.dbConf:
                self.dbConf[x] = {}
            for y in database[DbType][x]:
                if y not in self.dbConf[x]:
                    self.dbConf[x][y] = database[DbType][x][y]
        self.dbContect()
        
    def dbContect(self):
        self.db = {}
        self.coon = {}
        for x in self.dbConf :
            if x not in self.db:
                self.db[x] = {}
                self.coon[x] = {}   
            for y in self.dbConf[x]:
                coon = MySQLdb.connect( **self.dbConf[x][y] )
                if y not in self.db[x]:
                    self.db[x][y] = coon.cursor(cursorclass=MySQLdb.cursors.DictCursor) 
                    self.coon[x][y] = coon
                    
      
    def bmquery(self,sql,baseName='order'):
        sqlstr = sql.lstrip().rstrip(' ')
        sqltype = False
        sqltitle = sqlstr[0:6].lower()
        if 'select' == sqltitle:
            sqltype = "read"
        elif 'insert' == sqltitle or 'delete' == sqltitle or 'update' == sqltitle :
            sqltype = "write"
        if sqltype:
            ret = {'status':False}
            data = self.db[baseName][sqltype].execute(sql);
            if 'read' == sqltype :
                if 0 < data :
                    ret['status'] = True
                    ret['data'] = self.db[baseName][sqltype].fetchall()
            else:
                self.coon[baseName][sqltype].commit()
                ret['status'] = True
            return ret
        else:
            return {'status':False,'msg':"sql语句有问题，请认真检查语句 --" + sql + "--后，重试"}